package com.gzsxy.NIO;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author xiaolong
 * @version 1.0
 * @description: 实现文件的拷贝
 * @date 2022/4/23 19:58
 */
public class NIOFileChannel03 {

    public static void main(String[] args) throws Exception {

        FileInputStream fileInputStream = new FileInputStream("1.txt");
        FileChannel fileChannel01 = fileInputStream.getChannel();

        FileOutputStream fileOutputStream1 = new FileOutputStream("2.txt");
        FileChannel fileChannel02 = fileOutputStream1.getChannel();

        ByteBuffer byteBuffer = ByteBuffer.allocate(512);

        while (true){
            //这里有一个重要的操作， 一定不要忘记
            byteBuffer.clear();//清空buffer，不然当读到最后一个limit=position时 默认返回read = 0导致不断循环

            int read = fileChannel01.read(byteBuffer);
            System.out.println("read=" +read);
            //表示读完
            if (read == -1){
                break;
            }
            //将buffer 中的数据写入到fileChannel02 --2.txt
            byteBuffer.flip();
            fileChannel02.write(byteBuffer);
        }

        fileOutputStream1.close();
        fileInputStream.close();

    }
}
